"use strict";

const semver = require("semver");
const log = require("@test-cli/log");

const LOWEST_NODE_VERSION = "12.0.0"; // node版本号

class Command {
  constructor(argv) {
    // log.verbose("Command constructor", argv);
    if (!argv) {
      throw new Error("参数不能为空");
    }

    if (!Array.isArray(argv)) {
      throw new Error("参数必须是数组");
    }

    if (argv.length < 1) {
      throw new Error("参数不能为空");
    }

    this._argv = argv;
    let runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve();
      chain
        .then(() => this.checkNodeVersion())
        .then(() => this.initArgs())
        .then(() => this.init())
        .then(() => this.exec())
        .catch(e => {
          log.error(e.message);
        });
    });
  }

  initArgs() {
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1);
  }

  // 检查node版本号
  checkNodeVersion() {
    // 1.获取当前版本号
    // 2.比对版本号
    const currentVersion = process.version;
    const lowerNodeVersion = LOWEST_NODE_VERSION;

    if (!semver.gte(currentVersion, lowerNodeVersion)) {
      throw new Error(`test-cli 需要安装 ${lowerNodeVersion} 以上版本的Node`);
    }
  }

  init() {
    throw new Error("init 必须实现");
  }

  exec() {
    throw new Error("exec 必须实现");
  }
}

module.exports = Command;
